package service

import (
	"seat-service/initialization"
	"seat-service/model"
	"seat-service/model/dto"
)

type MessageService struct {
}

func (m *MessageService) CreateAnnouncement(announcement model.Message) error {
	err := initialization.DB.Create(&announcement).Error
	return err
}

func (m *MessageService) QueryAnnouncement(p dto.PageParam) (count int64, result []model.Message, err error) {
	var data string
	if p.Data == nil {
		data = ""
	} else {
		data = p.Data.(string)
	}
	offset := (p.PageNo - 1) * p.PageSize
	err = initialization.DB.Model(&model.Message{}).Where("title like ?", "%"+data+"%").Limit(p.PageSize).Offset(offset).Find(&result).Count(&count).Error
	return
}

func (m *MessageService) UpdateAnnouncement(newAnnouncement model.Message) error {
	updateFields := map[string]interface{}{
		"status":   newAnnouncement.Status,
		"head_img": newAnnouncement.HeadImg,
		"content":  newAnnouncement.Content,
		"title":    newAnnouncement.Title,
		"type":     newAnnouncement.Type,
	}
	if newAnnouncement.Status == 0 {
		updateFields["status"] = newAnnouncement.Status
	}

	err := initialization.DB.Model(&model.Message{}).Where("id = ?", newAnnouncement.ID).Updates(updateFields).Error
	return err
}

func (m *MessageService) QueryAnnouncementById(id int) (result model.Message, err error) {
	err = initialization.DB.Where("id = ?", id).First(&result).Error
	return
}

func (m *MessageService) DeleteAnnouncementByIds(ids dto.DeleteAnnouncementIds) error {
	var message model.Message
	err := initialization.DB.Where("id in (?)", ids.AnnouncementIds).Delete(&message).Error
	return err
}

func (m *MessageService) SelectAllMessage() (result []model.Message, err error) {
	err = initialization.DB.Where("type = 'OFFICIAL'").Find(&result).Error
	return
}

func (m *MessageService) SelectUserMessage() (result []model.Message, err error) {
	err = initialization.DB.Where("type = 'USER'").Find(&result).Error
	return
}
